package org.ThreadDemo.sync;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Mycache1 {
    private volatile Map<String,Object> map  = new HashMap<>();

    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key, Object value){

        rwLock.writeLock().lock();


        try {
            System.out.println(Thread.currentThread().getName()+"正在写操作"+key);

            TimeUnit.MILLISECONDS.sleep(5000);

            map.put(key,value);

            System.out.println(Thread.currentThread().getName()+"写完了"+key);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally{
            rwLock.writeLock().unlock();
        }

    }

    public Object get(String key){

        rwLock.readLock().lock();

        Object result = null;
        try {

            System.out.println(Thread.currentThread().getName()+"正在读取操作"+key);
            TimeUnit.MILLISECONDS.sleep(5000);
            result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"取完了"+key);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally{
            rwLock.readLock().unlock();
        }

        return result;
    }
}
public class ReadWriteLockDemo01 {
    public static void main(String[] args) {

        Mycache1 myCache = new Mycache1();

        for(int i =1;i<=5; i++){
            final int num = 1;
            new Thread(
                    ()->{
                        myCache.put(num+"",num+"");
                    },String.valueOf(i)
            ).start();
        }

        for(int i =1;i<=5; i++){
            final int num = 1;
            new Thread(
                    ()->{
                        myCache.get(num+"");
                    },String.valueOf(i)
            ).start();
        }


    }
}
